package com.ithaima.a_cookie;

import com.ithaima.a_cookie.com.itheima.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/lastTimeServlet")
public class LastTimeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取所有的Cookie数组
    /*    Cookie[] cookies = request.getCookies();
        //遍历数组查找lastTimeCookie对象
        Cookie cookie = null;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if ("lastTimeCookie".equals(c.getName())) {
                    cookie = c;
                }
            }
        }*/
        //查找cookie
        Cookie cookie = CookieUtils.findCookieByName(request, "lastTimeCookie");
        PrintWriter writer = response.getWriter();
        //判断cookie是否为null
        if (cookie == null) {
            //首次访问
            writer.write("<h3>欢迎你首次访问<h3>");
        } else {
            //不是第一次获取cookie的值
            String time = cookie.getValue();
//            时间显示到页面
            writer.write("<h3>欢迎你回来,上次访问时间为:" + time + "<h3>");
        }
//            无论是否首次访问,使用Cookie记录上次访问时间(不能存储空格)
        Cookie c = new Cookie("lastTimeCookie", new Date().toLocaleString().replaceAll(" ", ""));
        //持久化保存
        c.setMaxAge(60 * 60 * 24 * 3);
        response.addCookie(c);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
